<script setup>
// 编译语法糖，不需要export default，直接暴露所有内容
import { computed, ref, reactive, watchEffect, watch } from "vue"; // vue3的响应式API需要从vue中引入
// vue3使用ref和reactive来定义响应式数据
// ref：定义基本类型的响应式数据
// reactive：定义对象类型的响应式数据

const name = computed(() => {
  // 可读计算属性，只读，不能修改
  return "Hello World";
});

// 响应式数据示例
const message = ref("Hello Vue 3!");
const user = reactive({
  name: "张三",
  age: 25,
});
const array = reactive([1, 2, 3, 4, 5]);
const count2 = ref(0);
const count4 = ref(0);

const count3 = computed({
  get() {
    return count2.value;
  },
  set(value) {
    // 设置count3的值时，会触发setter
    count4.value = value + 2;
    count2.value++;
  },
});

defineProps({
  msg: String,
});

watchEffect(() => {
  //函数中任何响应式数据发生变化，都会触发
  let a = count3.value + count2.value;
  let b = name.value;
  console.log("watchEffect监听的值发生了变化", a, b);
});

watch(count2, (newVal, oldVal) => {
  //监听count2的值发生变化
  console.log("watch监听count2的值发生了变化", newVal, oldVal);
});

// 自定义指令
const vDirective = {
  mounted(el, binding) {
    el.addEventListener("click", () => {
      console.log("自定义指令被点击了");
    });
  },
};
</script>

<template>
  <div>
    <h1>{{ name }}</h1>
    <h1>{{ count2 }}</h1>
    <h1>{{ count3 }}</h1>
    <button v-directive @click="count2++">点击</button>
    <button @click="count3++">触发setter</button>
    <!-- setter只有在赋值时才会触发 -->
    <h1>{{ count4 }}</h1>
    <div id="teleport-container"></div>
  </div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
